﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using HR.Appointments.Service;

public partial class NewEntry : EmployeePage
{
    #region Events
    protected void Page_Load(object sender, EventArgs e)
    {
        _imgConfirm.Visible = IsLoggedIn;
        if (IsLoggedIn)
        {
            
			_lbtnConfig.Visible = true;
            _lbtnCompany.Visible = false;
            _lblChangeCompany.Visible = true;
            _lblNewEntryCompany.Visible = false;
            _lbtnConfigSub.Visible = true;
            _lbtnCompanyBookingSub.Visible = true;
            
        }
        else
        {
			_lbtnConfig.Visible = false;
            _lbtnCompany.Visible = true;
            _lbtnCompanyBooking1.Visible = false;
            _lblChangeCompany.Visible = false;
            _lblNewEntryCompany.Visible = true;
            _lbtnConfigSub.Visible = false;
            _lbtnCompanyBookingSub.Visible = false;


        }

        bool change = Convert.ToBoolean(Request.QueryString["Change"]);
        if (change)
        {
            CheckCredentials();
        }
		if(!IsPostBack)
		{
			if (change && IsLoggedIn)
			{
				var company = Facade.Employee().GetCompanyInstance(
					GetCompanyIdFromCookie());

				_txtCompanyName.Text = company.Name;
				_txtNationalID.Text = company.NationalId;
				_txtEmail.Text = company.Email;
				_txtPhoneNumber.Text = company.Phone;
                _txtDescription.Text = company.Description;
                _txtUsername.Text = company.Username;
                _txtPassword.Text = company.Password;
                _ddlDelayTime.Text = company.DelayTime.ToString();

			}
		}
    }

    protected void _btnNewCompany_Click(object sender, EventArgs e)
    {
        var company = CompanyEntity.Create(
        _txtNationalID.Text,
        _txtDescription.Text,
        _txtCompanyName.Text,
        _txtPhoneNumber.Text,
        _txtEmail.Text,
        _txtPicture.FileName,
        _txtUsername.Text,
        _txtPassword.Text,
        Convert.ToInt32(_ddlDelayTime.Text));

        // Before attempting to save the file, verify
        // that the FileUpload control contains a file.
        if (_txtPicture.HasFile)
        {
            // Call a helper method routine to save the file.
            company.Picture = "~/myndir/" + SaveFile(_txtPicture.PostedFile);
        }

        if (Convert.ToBoolean(Request.QueryString["Change"]))
        {
            if (IsLoggedIn)
            {
                try
                {
                    company.CompanyId = GetCompanyIdFromCookie();
                    if (!_txtPicture.HasFile)
                    {
                        var companyClone = Facade.Employee().GetCompanyInstance(company.CompanyId);
                        company.Picture = companyClone.Picture;
                    }
                    Facade.Employee().UpdateCompany(company);
                }
                catch (SubmitException)
                {
                    Page.ClientScript.RegisterStartupScript(GetType(), "ErrorAlert", "alert('Ekki tókst að uppfæra.');", true);
                    return;
                }
                Server.Transfer("~/Config.aspx", true);
            }
        }
        else
        {
            try
            {
                Facade.Anonymous().CreateCompany(company);
            }
            catch (SubmitException)
            {
                Page.ClientScript.RegisterStartupScript(GetType(), "ErrorAlert", "alert('Ekki tókst að stofna.');", true);
                return;
            }
            Server.Transfer("~/Company.aspx", true);
        }
    }
    #endregion

    #region Link Transfer
    protected void _ibmHomePage_Click(object sender, ImageClickEventArgs e)
	{
        if (!IsPostBack || (e.X != 0 && e.Y != 0))
        {
            Server.Transfer("~/Company.aspx",true);
        }
	}

    protected void _lbtnCompany_Click(object sender, EventArgs e)
    {
        Server.Transfer("~/Company.aspx", true);
    }

    protected void _lbtnCompanyBooking_Click(object sender, EventArgs e)
    {
        Server.Transfer("~/Config.aspx", true);
    }

    protected void _lbtnCompanyBookingSub_Click(object sender, EventArgs e)
    {
        Server.Transfer("~/CompanyBooking.aspx", true);
    }
    protected void _lbtnConfigSub_Click(object sender, EventArgs e)
    {
        Server.Transfer("~/Config.aspx", true);
    }
    #endregion

    #region Private Methods
    private string SaveFile(HttpPostedFile file)
    {
        // Specify the path to save the uploaded file to.
        string savePath = @"C:\dev\verk2\src\HR.Appointments.Web\Myndir\";

        // Get the name of the file to upload.
        string fileName = _txtPicture.FileName;

        // Create the path and file name to check for duplicates.
        string pathToCheck = savePath + fileName;

        // Create a temporary file name to use for checking duplicates.
        string tempfileName = "";

        // Check to see if a file already exists with the
        // same name as the file to upload.        
        if (System.IO.File.Exists(pathToCheck))
        {
            int counter = 2;
            while (System.IO.File.Exists(pathToCheck))
            {
                // if a file with this name already exists,
                // prefix the filename with a number.
                tempfileName = counter.ToString() + fileName;
                pathToCheck = savePath + tempfileName;
                counter++;
            }

            fileName = tempfileName;

            // Notify the user that the file name was changed.
            //UploadStatusLabel.Text = "A file with the same name already exists." +
              //  "<br />Your file was saved as " + fileName;
        }
        else
        {
            // Notify the user that the file was saved successfully.
            //UploadStatusLabel.Text = "Your file was uploaded successfully.";
        }

        // Append the name of the file to upload to the path.
        savePath += fileName;

        // Call the SaveAs method to save the uploaded
        // file to the specified directory.
        _txtPicture.SaveAs(savePath);

        return fileName;

    }
    #endregion
    
	protected void _lbtnCompanyBooking1_Click(object sender, EventArgs e)
	{
		Server.Transfer("~/CompanyBooking.aspx", true);
	}
	protected void _lbtnConfig_Click(object sender, EventArgs e)
	{
		Server.Transfer("~/Config.aspx", true);
	}
}
